﻿package com.gobang.netmode.sendandreceive;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

public class SendAndReceive {
	Socket socket;
	BufferedInputStream ins; // 输入流
	BufferedOutputStream outs;// 输出流
	ObjectInputStream objInS; // 对象输入流
	ObjectOutputStream objOutS; // 对象输出流
	long time;

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
		try {
			ins = new BufferedInputStream(socket.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 获得输入流
	}

	public SendAndReceive(Socket socket) {
		// TODO Auto-generated constructor stub
		this.socket = socket;
		try {
			ins = new BufferedInputStream(socket.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 获得输入流
		time = System.currentTimeMillis();
	}

	public synchronized boolean sendMessage(Message message) {
//		long now = System.currentTimeMillis();
//		if((now - time) < 100){
//			try {
//				Thread.sleep(100 -(now - time));
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		try {
			if (socket != null && !socket.isClosed()) {
				outs = new BufferedOutputStream(socket.getOutputStream());
				objOutS = new ObjectOutputStream(outs);
				message.setTime();
				objOutS.writeObject(message);
				objOutS.flush();
				time = System.currentTimeMillis();
				return true;
			} else {
				return false;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public  Message receiveMessage() throws ClassNotFoundException {
		Message message = new Message();
		try {
			if (socket != null && !socket.isClosed()) {
				objInS = new ObjectInputStream(ins);//阻塞
				message = (Message) objInS.readObject();
				return message;
			} else {
				return null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	public void close(){
		try{
			socket.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
